import Dialog from 'tdesign-miniprogram/dialog/index';
import Toast from 'tdesign-miniprogram/toast/index';

Page({
  data: {
    cartGroupData: null,
    cardList: [],
    selectGoods: [],
    totalAmount: 0,
    totalDiscountAmount: 0,
    pageLoading: false,
    isAllSelected: false,
  },

  onShow() {
    this.getTabBar().init();
    wx.startPullDownRefresh();
  },
  onPullDownRefresh() {
    this.getCartData();
    this.setData({
      isAllSelected: false,
    });
  },

  async saveGoodNum(db, openId) {
    const { cardList } = this.data;
    for (let i = 0; i < cardList.length; i++) {
      await db
        .collection('carts')
        .where({ _openid: openId })
        .update({
          data: {
            [`goods.${i}.num`]: cardList[i].num,
            [`goods.${i}.isSelected`]: cardList[i].isSelected,
          },
        });
    }
  },

  async getCartData() {
    this.setData({
      pageLoading: true,
    });
    const db = wx.cloud.database();
    const openId = wx.getStorageSync('openId');

    if (this.data.cardList.length) {
      await this.saveGoodNum(db, openId);
    }
    const { data: cartDataList } = await db.collection('carts').where({ _openid: openId }).get();
    const goods = cartDataList[0]?.goods?.length ? cartDataList[0]?.goods : [];
    if (goods.length) {
      const cardList = [];
      for (let i = 0; i < goods.length; i++) {
        const { data: good } = await db.collection('goodList').where({ _id: goods[i].goodId }).get();
        cardList.push({ ...good[0], isSelected: goods[i].isSelected, num: goods[i].num, specs: goods[i].specs || '' });
      }
      this.setData({
        cardList,
      });
      if (cardList.findIndex((i) => !i.isSelected) < 0) {
        this.setData({
          isAllSelected: true,
        });
      }
      this.setData({
        selectGoods: cardList.filter((i) => i.isSelected),
      });
      this.getTotalAmount();
    } else {
      this.setData({
        cardList: [],
      });
    }
    this.setData({
      pageLoading: false,
    });
    wx.stopPullDownRefresh();
  },

  refreshData() {
    this.getCartGroupData().then((cartGroupData) => {
      let isEmpty = true;
      // 一些组件中需要的字段可能接口并没有返回，或者返回的数据结构与预期不一致，需要在此先对数据做一些处理
      // 统计门店下加购的商品是否全选、是否存在缺货/无货
      for (const store of cartGroupData) {
        console.log(store);
        store.isSelected = true; // 该门店已加购商品是否全选
        store.storeStockShortage = false; // 该门店已加购商品是否存在库存不足
        if (!store.shortageGoodsList) {
          store.shortageGoodsList = []; // 该门店已加购商品如果库存为0需单独分组
        }
        //#region
        // for (const activity of store?.promotionGoodsList) {
        //   console.log(activity);
        //   activity.goodsPromotionList = activity.goodsPromotionList.filter((goods) => {
        //     goods.originPrice = undefined;

        //     // 统计是否有加购数大于库存数的商品
        //     if (goods.quantity > goods.stockQuantity) {
        //       store.storeStockShortage = true;
        //     }
        //     // 统计是否全选
        //     if (!goods.isSelected) {
        //       store.isSelected = false;
        //     }
        //     // 库存为0（无货）的商品单独分组
        //     if (goods.stockQuantity > 0) {
        //       return true;
        //     }
        //     store.shortageGoodsList.push(goods);
        //     return false;
        //   });

        //   if (activity.goodsPromotionList.length > 0) {
        //     isEmpty = false;
        //   }
        // }
        //#endregion
        if (store.shortageGoodsList.length > 0) {
          isEmpty = false;
        }
      }
      cartGroupData.invalidGoodItems = cartGroupData.invalidGoodItems?.map((goods) => {
        goods.originPrice = undefined;
        return goods;
      });
      cartGroupData.isNotEmpty = !isEmpty;
      this.setData({ cartGroupData });
    });
  },

  findGoods(_id) {
    let currentStore;
    let currentActivity;
    let currentGoods;
    const { storeGoods } = this.data.cartGroupData;
    for (const store of storeGoods) {
      for (const activity of store.promotionGoodsList) {
        for (const goods of activity.goodsPromotionList) {
          if (goods._id === _id) {
            currentStore = store;
            currentActivity = currentActivity;
            currentGoods = goods;
            return {
              currentStore,
              currentActivity,
              currentGoods,
            };
          }
        }
      }
    }
    return {
      currentStore,
      currentActivity,
      currentGoods,
    };
  },

  // 注：实际场景时应该调用接口获取购物车数据
  getCartGroupData() {
    const { cartGroupData } = this.data;
    // if (!cartGroupData) { //mock
    //   return fetchCartGroupData();
    // }

    this.setData({ cartGroupData });
  },

  // 选择单个商品
  // 注：实际场景时应该调用接口更改选中状态
  selectGoodsService({ spuId, skuId, isSelected }) {
    this.findGoods(spuId, skuId).currentGoods.isSelected = isSelected;
    return Promise.resolve();
  },

  // 全选门店
  // 注：实际场景时应该调用接口更改选中状态
  selectStoreService({ storeId, isSelected }) {
    const currentStore = this.data.cartGroupData.storeGoods.find((s) => s.storeId === storeId);
    currentStore.isSelected = isSelected;
    currentStore.promotionGoodsList.forEach((activity) => {
      activity.goodsPromotionList.forEach((goods) => {
        goods.isSelected = isSelected;
      });
    });
    return Promise.resolve();
  },

  // 加购数量变更
  // 注：实际场景时应该调用接口
  changeQuantityService({ spuId, skuId, quantity }) {
    this.findGoods(spuId, skuId).currentGoods.quantity = quantity;
    return Promise.resolve();
  },

  // 删除加购商品
  // 注：实际场景时应该调用接口
  deleteGoodsService({ spuId, skuId }) {
    function deleteGoods(group) {
      for (const gindex in group) {
        const goods = group[gindex];
        if (goods.spuId === spuId && goods.skuId === skuId) {
          group.splice(gindex, 1);
          return gindex;
        }
      }
      return -1;
    }
    const { storeGoods, invalidGoodItems } = this.data.cartGroupData;
    for (const store of storeGoods) {
      for (const activity of store.promotionGoodsList) {
        if (deleteGoods(activity.goodsPromotionList) > -1) {
          return Promise.resolve();
        }
      }
      if (deleteGoods(store.shortageGoodsList) > -1) {
        return Promise.resolve();
      }
    }
    if (deleteGoods(invalidGoodItems) > -1) {
      return Promise.resolve();
    }
    return Promise.reject();
  },

  // 清空失效商品
  // 注：实际场景时应该调用接口
  clearInvalidGoodsService() {
    this.data.cartGroupData.invalidGoodItems = [];
    return Promise.resolve();
  },

  getTotalAmount() {
    let totalAmount = 0;
    let totalDiscountAmount = 0;
    this.data.selectGoods.forEach((i) => {
      totalAmount += (i.num || 1) * i.minSalePrice;
      totalDiscountAmount += (i.num || 1) * i.maxLinePrice;
    });
    this.setData({
      totalAmount,
      totalDiscountAmount,
    });
  },

  onGoodsSelect(e, all, isAllSelected) {
    const { _id } = e.detail;
    const goodIndex = this.data.cardList.findIndex((i) => i._id === _id);
    const { cardList } = this.data;
    cardList[goodIndex].isSelected = all ? isAllSelected : !cardList[goodIndex].isSelected;
    this.setData({ cardList });

    // const arr = this.data.selectGoods
    // if (this.data.selectGoods.includes(_id)) {
    //   const index = arr.findIndex((i) => i === _id)
    //   arr.splice(index, 1)
    //   this.setData({
    //     selectGoods: arr
    //   })
    // } else {
    //   this.setData({
    //     selectGoods: arr.concat(_id)
    //   })
    // }
    this.setData({
      selectGoods: this.data.cardList.filter((i) => i.isSelected),
    });
    const { selectGoods } = this.data;
    if (!all) {
      if (selectGoods.length === cardList.length) {
        this.setData({
          isAllSelected: true,
        });
      } else {
        this.setData({
          isAllSelected: false,
        });
      }
    }

    this.getTotalAmount();
    !all &&
      Toast({
        context: this,
        selector: '#t-toast',
        message: `${cardList[goodIndex].isSelected ? '选择' : '取消'}${cardList[goodIndex].title}`,
        icon: '',
      });
  },

  onStoreSelect(e) {
    const {
      store: { storeId },
      isSelected,
    } = e.detail;
    this.selectStoreService({ storeId, isSelected }).then(() => this.refreshData());
  },
  onQuantityChange(e) {
    const { _id, num } = e.detail;
    const goodIndex = this.data.cardList.findIndex((i) => i._id === _id);
    const { cardList } = this.data;
    cardList[goodIndex].num = num;
    this.setData({ cardList });
    this.getTotalAmount();
    // 加购数量超过库存数量
    // if (quantity > stockQuantity) {
    //   // 加购数量等于库存数量的情况下继续加购
    //   if (currentGoods.quantity === stockQuantity && quantity - stockQuantity === 1) {
    //     Toast({
    //       context: this,
    //       selector: '#t-toast',
    //       message: '当前商品库存不足',
    //     });
    //     return;
    //   }
    //   Dialog.confirm({
    //     title: '商品库存不足',
    //     content: `当前商品库存不足，最大可购买数量为${stockQuantity}件`,
    //     confirmBtn: '修改为最大可购买数量',
    //     cancelBtn: '取消',
    //   })
    //     .then(() => {
    //       this.changeQuantityService({
    //         spuId,
    //         skuId,
    //         quantity: stockQuantity,
    //       }).then(() => this.refreshData());
    //     })
    //     .catch(() => { });
    //   return;
    // }
    // this.changeQuantityService({ spuId, skuId, quantity }).then(() => this.refreshData());
  },
  goCollect() {
    /** 活动肯定有一个活动ID，用来获取活动banner，活动商品列表等 */
    const promotionID = '123';
    wx.navigateTo({
      url: `/pages/promotion-detail/index?promotion_id=${promotionID}`,
    });
  },

  goGoodsDetail(e) {
    const { _id: spuId } = e.detail.goods;
    wx.navigateTo({
      url: `/pages/goods/details/index?spuId=${spuId}`,
    });
  },

  clearInvalidGoods() {
    // 实际场景时应该调用接口清空失效商品
    this.clearInvalidGoodsService().then(() => this.refreshData());
  },

  onGoodsDelete(e) {
    const { _id } = e.detail;
    const index = this.data.cardList.findIndex((i) => i._id === _id);
    Dialog.confirm({
      content: '确认删除该商品吗?',
      confirmBtn: '确定',
      cancelBtn: '取消',
    }).then(async () => {
      const arr = this.data.cardList;
      arr.splice(index, 1);
      this.setData({
        cardList: arr,
      });
      const openId = wx.getStorageSync('openId');
      const db = wx.cloud.database();
      await db
        .collection('carts')
        .where({
          _openid: openId,
        })
        .update({
          data: {
            goods: db.command.pull({ goodId: _id }),
          },
          success: () => {
            this.getCartData();
          },
        });
    });
  },

  onSelectAll() {
    // const { isAllSelected } = event?.detail ?? {};
    // console.log('isAllSelected', isAllSelected);
    this.data.cardList.forEach((i) => {
      this.onGoodsSelect({ detail: { _id: i._id } }, true, !this.data.isAllSelected);
    });
    this.setData({
      isAllSelected: !this.data.isAllSelected,
    });
    Toast({
      context: this,
      selector: '#t-toast',
      message: `${!this.data.isAllSelected ? '你不饿？' : '撑得死！'}`,
    });
    // 调用接口改变全选
  },

  async onToSettle() {
    const cartList = this.data.cardList.filter((g) => g.isSelected);
    await this.getCartData();
    if (cartList.findIndex((i) => i.residueNum < i.num) >= 0) {
      Toast({
        context: this,
        selector: '#t-toast',
        message: '商品库存不足,请重新选择',
      });
      return;
    }
    wx.setStorageSync('cartList', JSON.stringify(cartList));
    wx.navigateTo({ url: '/pages/order/order-confirm/index?type=cart' });
  },
  onGotoHome() {
    wx.switchTab({ url: '/pages/home/home' });
  },
});
